﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ZhaoXi_Core_WebApi.Utility
{
    /// <summary>
    /// Resource 资源过滤器 (可以发生的更早  可以在控制器的实例化之前，流程的最后。他适合做缓存---可以避免控制器)
    /// Result 结果过滤器
    /// </summary>
    public class CustomerResourceFilterAttribute : Attribute, IResourceFilter
    {
        private static Dictionary<string, object> dictionaryCache = new Dictionary<string, object>();

        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            string key = context.HttpContext.Request.Path.ToString();
            if (dictionaryCache.ContainsKey(key))//如果缓存里面包含了
            {
                context.Result = dictionaryCache[key] as ObjectResult;    //Result 短路器
            }
            Console.WriteLine("this is CustomResourceFilterAttribute.OnResourceExecuting");
        }

        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            ///把数据存储缓存；
            //Key---path;
            string key = context.HttpContext.Request.Path.ToString();
            ObjectResult objectResult = context.Result as ObjectResult;
            dictionaryCache[key] = objectResult;
            Console.WriteLine("this is CustomResourceFilterAttribute.OnResourceExecuted");
        }
    }
}
